package co.yixiang.modules.shop.service.impl;

import co.yixiang.modules.shop.domain.YxProductBase;
import co.yixiang.modules.shop.domain.YxProductStockOut;
import co.yixiang.modules.shop.domain.YxStoreCategory;
import co.yixiang.modules.shop.domain.YxStoreProduct;
import co.yixiang.modules.shop.repository.ProductStockOutRepository;
import co.yixiang.modules.shop.repository.YxProductBaseRepository;
import co.yixiang.modules.shop.repository.YxStoreProductRepository;
import co.yixiang.modules.shop.service.ProductStockOutService;
import co.yixiang.modules.shop.service.dto.ProductStockOutQueryCriteria;
import co.yixiang.modules.shop.service.dto.YxProductStockOutDTO;
import co.yixiang.modules.shop.service.mapper.YxProductStockOutMapper;
import co.yixiang.utils.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;

/**
 * @author frq
 * @date 2020-5-15
 */
@Service
@Transactional(rollbackFor = Exception.class, propagation = Propagation.SUPPORTS, readOnly = true)
public class ProductStockOutServiceImpl implements ProductStockOutService {
    @Autowired
    private ProductStockOutRepository productStockOutRepository;

    @Autowired
    private YxProductStockOutMapper productStockOutMapper;



    @Autowired
    private YxProductBaseRepository productBaseRepository;

    @Autowired
    private YxStoreProductRepository yxStoreProductRepository;
    @Autowired
    private YxProductBaseRepository  yxProductBaseRepository;
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void save(YxProductStockOut productStockOut) {
        productStockOutRepository.save(productStockOut);
    }

    /**
     * 分页查询商城商品详情
     *
     * @param criteria
     * @param pageable
     * @return
     */
    @Override
    public Map<String, Object> queryAll(ProductStockOutQueryCriteria criteria, Pageable pageable) {
        Page<YxProductStockOut> page = productStockOutRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder), pageable);
        Map<String, Object> map = new LinkedHashMap<>(2);
        List<YxProductStockOutDTO> listData = new ArrayList<>();
        for (YxProductStockOut dto : page.getContent()) {
            YxProductStockOutDTO productStockOut = productStockOutMapper.toDto(dto);
            Optional<YxProductBase> optional = productBaseRepository.findById(dto.getBaseProductId());
            if (optional.isPresent()) {
                //抓取商城数据的时候已经写入数据来源，这里不用查字典表了
//                String dataSourceName = productStockOutRepository.findDataSourceName("out_product_data_source", dto.getDataSource());
//                productStockOut.setDataSource(dataSourceName);
                productStockOut.setBaseProductName(optional.get().getName());
                productStockOut.setSalesReference(optional.get().getSalesReference());
            }
            listData.add(productStockOut);
        }
        map.put("content", listData);
        map.put("totalElements", page.getTotalElements());
        return map;
    }

    /**
     * 按条件不分页查询
     *
     * @param criteria 条件参数
     * @return
     */
    @Override
    public List<YxProductStockOutDTO> queryAll(ProductStockOutQueryCriteria criteria) {
        return productStockOutMapper.toDto(productStockOutRepository.findAll((root, criteriaQuery, criteriaBuilder) -> QueryHelp.getPredicate(root, criteria, criteriaBuilder)));
    }

    /**
     * 根据ID查询
     *
     * @param id
     * @return
     */
    @Override
    public YxProductStockOut findById(Integer id) {
        YxProductStockOut productStockOut = productStockOutRepository.findById(id).orElseGet(YxProductStockOut::new);
        return productStockOut;
    }

    /**
     * @param all      待导出的数据
     * @param response /
     * @throws IOException
     */
    @Override
    public void download(List<YxProductStockOutDTO> all, HttpServletResponse response) throws IOException {
        List<Map<String, Object>> list = new ArrayList<>();
        for (YxProductStockOutDTO productStockOut : all) {
            Map<String, Object> map = new LinkedHashMap<>();
            map.put("标题", productStockOut.getTitle());
            map.put("商品名称", productStockOut.getPname());
            map.put("品牌", productStockOut.getBrand());
            map.put("产地", productStockOut.getPlace());
            map.put("毛重", productStockOut.getWeight());
            map.put("规格", productStockOut.getSpecs());
            map.put("价格", productStockOut.getPrice());
            map.put("数据来源", productStockOut.getDataSource());
            map.put("创建日期", productStockOut.getAddTime());
            list.add(map);
        }
        FileUtil.downloadExcel(list, response);
    }

    /**
     * 查询商品分类ID
     *
     * @param baseId
     * @return
     */
    @Override
    public Integer findGoodsCateId(Integer baseId) {
        return productStockOutRepository.findGoodsCateId(baseId);
    }

    /**
     * 逻辑删除
     *
     * @param id
     */
    @Override
    public void updateDel(Integer id, Integer isDel) {
        Optional<YxProductStockOut> optionalYxSystemUserTask = productStockOutRepository.findById(id);
        ValidationUtil.isNull(optionalYxSystemUserTask, "YxProductStockOut", "id", id);
        YxProductStockOut productStockOut = optionalYxSystemUserTask.get();
        productStockOut.setIsDel(isDel);
        productStockOutRepository.save(productStockOut);
    }
    /**
     * 加入内部商品库
     * @param ids
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void doAddInternal(Integer[] ids) {
        for (int i = 0; ids.length > i; i++) {
            YxProductStockOut productStockOut =findById(ids[i]);

            //查询商品分类ID
            Integer cateId = findGoodsCateId(productStockOut.getBaseProductId());
            YxStoreProduct storeProduct = new YxStoreProduct();
            storeProduct.setAddTime(OrderUtil.getSecondTimestampTwo());
            //商品图片
            storeProduct.setImage(productStockOut.getImage());
            //商品轮播图
            storeProduct.setSliderImage(StringUtils.isNotBlank(productStockOut.getPicUrl()) ? productStockOut.getPicUrl() : "");
            //商品名称
            storeProduct.setStoreName(productStockOut.getPname());
            //商品简介
            storeProduct.setStoreInfo(productStockOut.getTitle());
            //商品价格
            if(productStockOut.getPrice() == null || productStockOut.getPrice().equals("")){
                storeProduct.setPrice(new BigDecimal(0));

            }
            else{
                storeProduct.setPrice(new BigDecimal(productStockOut.getPrice()));
            }
            //销量
            storeProduct.setSales(StringUtils.isNotBlank(productStockOut.getSales()) ? Integer.parseInt(productStockOut.getSales()) : 0);
            //商户ID
            storeProduct.setMerId(0);
            //分类iD
            if (cateId != null) {
                YxStoreCategory storeCategory = new YxStoreCategory();
                storeCategory.setId(cateId);
                storeProduct.setStoreCategory(storeCategory);
            }
            //库存
            storeProduct.setStock(0);
            //是否上架
            storeProduct.setIsShow(0);
            //是否热卖
            storeProduct.setIsHot(1);
            //是否优惠
            storeProduct.setIsBenefit(0);
            //是否精品
            storeProduct.setIsBest(1);
            //是否新品
            storeProduct.setIsNew(1);
            //是否包邮
            storeProduct.setIsPostage(0);
            ///是否删除
            storeProduct.setIsDel(0);
            //是否代理
            storeProduct.setMerUse(0);
            //活动积分
            storeProduct.setGiveIntegral(BigDecimal.ZERO);
            //成本价
            storeProduct.setCost(BigDecimal.ZERO);
            //秒杀价
            storeProduct.setIsSeckill(0);
            //砍价状态
            storeProduct.setIsBargain(0);
            //是否优品推荐
            storeProduct.setIsGood(1);
            //虚拟销量
            storeProduct.setFicti(0);
            //浏览量
            storeProduct.setBrowse(0);
            // 产品描述
            storeProduct.setDescription(productStockOut.getTitle());
            //排序
            storeProduct.setSort(productStockOut.getId());
            //邮费
            storeProduct.setPostage(BigDecimal.ZERO);
            //产地
            storeProduct.setPlace(productStockOut.getPlace());
            //数据来源    0:手工添加    1:外部商品库
            storeProduct.setDataSource(1);
            storeProduct.setIsStockInvest(0);
            //查询商品销量参考值
            Optional<YxProductBase> optionalBase=yxProductBaseRepository.findById(productStockOut.getBaseProductId());
            if(optionalBase.isPresent()){
                YxProductBase yxProductBase=optionalBase.get();
                storeProduct.setSalesReference(yxProductBase.getSalesReference());
            }
            yxStoreProductRepository.save(storeProduct);
            //加入后，改状态
            productStockOut.setIsAddInnerStock(1);
            productStockOutRepository.save(productStockOut);
        }
    }
}
